﻿using Common.Cache;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Common.Aliyun
{
    /// <summary>
    /// STS授权凭证
    /// </summary>
    public class STSCredential
    {
        private static readonly MemoryCache memoryCache = new MemoryCache();
        /// <summary>
        /// STS AccessKeyID
        /// </summary>
        public string AccessKeyId { get; set; }
        /// <summary>
        /// STS AccessKeySecret
        /// </summary>
        public string AccessKeySecret { get; set; }
        /// <summary>
        /// STS securityToken
        /// </summary>
        public string SecurityToken { get; set; }
        /// <summary>
        /// STS 过期时间（GMT时间）
        /// </summary>
        public string Expiration { get; set; }
        internal static STSCredential GetSTSCredentail(string bucket, IConfiguration configuration, bool forUpload = false)
        {
            return memoryCache.GetOrAdd(bucket, b =>
            {
                STSPolicy policy = new STSPolicy
                {
                    Version = "1",
                    Statement = new List<PolicyStatement>
                    {
                        new PolicyStatement
                        {
                            Effect = PolicyEffect.允许,
                            Action = new List<string>(){ "oss:GetObject", "oss:GetObjectMeta" },
                            Resource = new List<string>(){ $"acs:oss:*:*:{b}/*" }
                        }
                    }
                };
                if (forUpload)
                {
                    policy.Statement.First().Action.Add("oss:PutObject");
                }
                STSAuthorization sts = new STSAuthorization(configuration);
                var stsResult = sts.STSGrant(nameof(OSSAccessAuthorize), policy);
                if (!stsResult)
                {
                    Console.WriteLine(stsResult.Message);
                }
                return stsResult?.Data;
            }, TimeSpan.FromMinutes(30));

        }
    }
}
